
var CryptoAgent = "";

function ComInit() {
	try{
		var eDiv = document.createElement("div");
		if (navigator.appName.indexOf("Internet") >= 0 || navigator.appVersion.indexOf("Trident") >= 0) {
			if (window.navigator.cpuClass == "x86") {
				eDiv.innerHTML = "<object id=\"CryptoAgent\" codebase=\"CryptoKit.Paperless.CMBChina.x86.cab\" classid=\"clsid:9035A591-F0B3-4C0A-9C18-B946BCA717DB\" ></object>";
			}
			else {
				eDiv.innerHTML = "<object id=\"CryptoAgent\" codebase=\"CryptoKit.Paperless.CMBChina.x64.cab\" classid=\"clsid:1822106B-AA30-4948-B963-E422FE68697A\" ></object>";
			}
		}
		document.body.appendChild(eDiv);
	    CryptoAgent = document.getElementById("CryptoAgent");	
	}
	catch(e)
	{
		alert(e);
		return;
	}
}
  
// Select certificate
function SelectCertificateOnClick() {
	try {                  
		document.getElementById("SelectCertResult").value = "false";
		var subjectDNFilter = document.getElementById("SubjectDNFilter").value;
		var issuerDNFilter = document.getElementById("IssuerDNFilter").value;
		var serialNumFilter = document.getElementById("SerialNumFilter").value;

		var bSelectCertResult = CryptoAgent.SelectCertificate(subjectDNFilter, issuerDNFilter, serialNumFilter, "");                        
		// Opera浏览器，NPAPI函数执行结果为false时，不能触发异常，需要自己判断返回值。
		if (!bSelectCertResult) 
		{
			var errorDesc = CryptoAgent.GetLastErrorDesc();
			alert(errorDesc);
			return;
		}
		document.getElementById("SelectCertResult").value = bSelectCertResult;
	}catch (e) {
		alert(e);
		var errorDesc = CryptoAgent.GetLastErrorDesc();
		alert(errorDesc);
	}
}

 function SignOnClick(signType, selectedAlg) {
	try {
		document.getElementById("Signature").value = "";
		var source = document.getElementById('SourceData').value;
		var signature = "";

		if ("Attach" == signType) {
			signature = CryptoAgent.SignMsgPKCS7(source, selectedAlg, true);
		}
		else{
			signature = CryptoAgent.SignMsgPKCS7(source, selectedAlg, false);
		}
		if (!signature) {
			var errorDesc = CryptoAgent.GetLastErrorDesc();
			alert(errorDesc);
			return;
		}
		document.getElementById("Signature").value = signature;
	} catch (e) {
		var errorDesc = CryptoAgent.GetLastErrorDesc();
		alert(errorDesc);
	}
}


export { ComInit, SignOnClick, SelectCertificateOnClick };